using MediatR;
using TerritoryGame.Application.Commands;
using TerritoryGame.Domain.Entities;
using TerritoryGame.Domain.Repositories;

namespace TerritoryGame.Application.Handlers.CommandHandlers;

public class StartGameCommandHandler : IRequestHandler<StartGameCommand, StartGameResult>
{
    private readonly IGameRoomRepository _gameRoomRepository;
    private readonly IGameRepository _gameRepository;

    public StartGameCommandHandler(IGameRoomRepository gameRoomRepository, IGameRepository gameRepository)
    {
        _gameRoomRepository = gameRoomRepository;
        _gameRepository = gameRepository;
    }

    public async Task<StartGameResult> Handle(StartGameCommand request, CancellationToken cancellationToken)
    {
        try
        {
            var room = await _gameRoomRepository.GetByIdAsync(request.RoomId);
            if (room == null)
            {
                return new StartGameResult
                {
                    Success = false,
                    ErrorMessage = "Room not found"
                };
            }

            if (room.Status != GameStatus.Waiting)
            {
                return new StartGameResult
                {
                    Success = false,
                    ErrorMessage = "Game already started or finished"
                };
            }

            if (room.Players.Count < 2)
            {
                return new StartGameResult
                {
                    Success = false,
                    ErrorMessage = "Need at least 2 players to start game"
                };
            }

            // 移除房主检查，任何玩家都可以开始游戏

            // Start the game
            room.StartGame();
            await _gameRoomRepository.UpdateAsync(room);

            // Get or create game
            var game = await _gameRepository.GetByRoomIdAsync(request.RoomId);
            if (game == null)
            {
                game = new Game(Guid.NewGuid(), room);
                await _gameRepository.AddAsync(game);
            }
            else
            {
                game.StartGame();
                await _gameRepository.UpdateAsync(game);
            }

            var players = room.Players.Select(p => new PlayerInfo
            {
                Id = p.Id,
                NickName = p.NickName,
                Color = p.Color,
                Score = p.CurrentScore,
                Area = 0, // 游戏开始时面积为0
                IsOnline = p.IsOnline
            }).ToList();

            // 添加日志来调试GameDuration
            Console.WriteLine($"StartGameCommand - Room GameDuration: {room.GameDuration}");
            
            return new StartGameResult
            {
                Success = true,
                GameDuration = room.GameDuration,
                Players = players
            };
        }
        catch (Exception ex)
        {
            return new StartGameResult
            {
                Success = false,
                ErrorMessage = ex.Message
            };
        }
    }
}
